package org.jsola.hr.web;

import org.apache.commons.lang3.StringUtils;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.HrMessageDTO;
import org.jsola.message.dto.ShortMessageDTO;
import org.jsola.message.service.ISmsSendService;
import org.jsola.message.vo.SmsSendLogVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author june
 */
@RestController("hrSmsSendController")
@RequestMapping(HrConstants.API_PATH + "/v1/messages/sms")
public class SendController implements ISendControllerAPI {

    @Autowired
    private ISmsSendService sendShortMessage;


    @Override
    @PostMapping
    public Result<Boolean> sendShortMessage(@RequestBody @Validated HrMessageDTO hrMessageDTO) {
        TokenUser tokenUser = null;
        if (StringUtils.isNotBlank(hrMessageDTO.getSiteId())) {
            tokenUser = new TokenUser();
            tokenUser.setSiteId(hrMessageDTO.getSiteId());
            tokenUser.setUserId("system");
        }
        ShortMessageDTO shortMessageDTO = hrMessageDTO.to(ShortMessageDTO.class);
        SmsSendLogVO smsSendLog = sendShortMessage.sendShortMessage(shortMessageDTO, tokenUser);
        if (smsSendLog.getIsSuccess()) {
            return Result.success(Boolean.TRUE);
        }
        return Result.fail(smsSendLog.getResult());
    }

    @Override
    @PostMapping("/captcha")
    public Result<Boolean> verifyCaptcha(@RequestBody @Validated HrMessageDTO hrMessageDTO) {
        TokenUser tokenUser = null;
        if (StringUtils.isNotBlank(hrMessageDTO.getSiteId())) {
            tokenUser = new TokenUser();
            tokenUser.setSiteId(hrMessageDTO.getSiteId());
            tokenUser.setUserId("system");
        }
        ShortMessageDTO shortMessageDTO = hrMessageDTO.to(ShortMessageDTO.class);
        boolean result = sendShortMessage.verifyCaptcha(shortMessageDTO, tokenUser);
        if (result) {
            return Result.success();
        } else {
            throw new ParamException("验证码错误");
        }
    }

}

